from machine import SoftI2C
from machine import Pin
from ssd1306 import SSD1306_I2C
import framebuf
import time
from dht22 import DHT22
# from dht import InvalidChecksum

WIDTH  = 128 # oled display width
HEIGHT = 64  # oled display height

# Init I2C using pins GP21 & GP20 (default I2C0 pins)
# i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=200000)
i2c = SoftI2C(scl=Pin(9), sda=Pin(8), freq=200000)
print("i2c addr: "+hex(i2c.scan()[0]).lower()) # Display device address
print("i2c conf: "+str(i2c))                   # Display I2C config

# Init oled display
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

# Raspberry Pi logo as 32x32 bytearray
buffer = bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?\x00\x01\x86@\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe3\x00\x00~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x01\xc1\x83\x80\x02A\x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc=\x80\x01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x008\x1c\x00\x00\x0c \x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")

dht = DHT22(Pin(28, Pin.IN, Pin.PULL_UP), dht11=True)

while True:

    # get sensor data.
    t, h = dht.read()
    print("Temperature: {}".format(t))
    print("Humidity: {}".format(h))

    # reading = sensor_temp.read_u16() * conversion_factor
    # Load the raspberry pi logo into the framebuffer (the image is 32x32)
    fb = framebuf.FrameBuffer(buffer, 32, 32, framebuf.MONO_HLSB)

    # Clear the oled display in case it has junk on it.
    oled.fill(0)

    # Blit the image from the framebuffer to the oled display
    oled.blit(fb, 96, 0)

    # Add some text
    oled.text("Temp: ",10,10)
    oled.text(str(t),50,10)
    oled.text("*C",90,10)

    oled.text("Humi: ",10,30)
    oled.text(str(h),50,30)
    oled.text("%",90,30)

    # Finally update the oled display so the image & text is displayed
    oled.show()

    time.sleep(1)





